import axios from 'axios'
import {ElMessage} from 'element-plus';
import router from '@/router';
import process from "sm-crypto/.eslintrc.js";


const service = axios.create({
    baseURL: "/api",
    timeout: 30000
});

const pendingPromise = new Promise(resolve => {
});

//请求拦截器
service.interceptors.request.use(
    config => {
        const token = localStorage.getItem("token");
        if (token) {
            config.headers = config.headers || {};
            config.headers["token"] = token;
        }
        return config;
    },
    error => {
        console.log("请求错误", error);
        return Promise.reject(error);
    }
);

service.interceptors.response.use(
    response => {
        if (response.config.responseType === "blob" || response.request.responseType === "blob") {
            return response;
        }

        const res = response.data;
        if (res.status !== 200) {
            ElMessage.error(res.message || "服务器异常");
        }

        if (res.status === 401 || res.status === 403) {
            ElMessage.error(res.message || "登录过期，请重新登录");
            router.push({
                path: '/login',
                query: {
                    redirect: window.location.pathname
                }
            });
        }

        return res;
    },
    error => {
        if (error.response.status === 401 || error.response.status === 403) {
            ElMessage.error(error.response.data.message || "登录过期，请重新登录");
            router.push({
                path: '/login',
                query: {
                    redirect: window.location.pathname
                }
            });
        }
        ElMessage.error("网络异常，请稍后再试");
        return Promise.reject(error);
    }
);





